package com.ruoyi.project.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ICollegeStaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;

/**
 * 学院教职员Service业务层处理
 *
 * @author ruoyi
 * @date 2020-10-07
 */
@Service
public class CollegeStaffServiceImpl implements ICollegeStaffService
{

    private static final Logger log = LoggerFactory.getLogger(CollegeStaffServiceImpl.class);

    @Autowired
    private CollegeStaffMapper collegeStaffMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CollegeMapper collegeMapper;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 查询学院教职员
     *
     * @param id 学院教职员ID
     * @return 学院教职员
     */
    @Override
    public CollegeStaff selectCollegeStaffById(Integer id)
    {
        return collegeStaffMapper.selectCollegeStaffById(id);
    }

    /**
     * 查询学院教职员列表
     *
     * @param collegeStaff 学院教职员
     * @return 学院教职员
     */
    @Override
    public List<CollegeStaff> selectCollegeStaffList(CollegeStaff collegeStaff)
    {
        if(collegeStaff.getTypeCode()!=null&&collegeStaff.getTypeCode() == 3){

            return collegeStaffMapper.selectCollegeRootList(collegeStaff);
        }else{
            collegeStaff.setTypeCode(2);
            return collegeStaffMapper.selectCollegeStaffList(collegeStaff);
        }
    }

    /**
     * 新增学院教职员
     *
     * @param collegeStaff 学院教职员
     * @return 结果
     */
    @Override
    public int insertCollegeStaff(CollegeStaff collegeStaff,SysUser sysUser)
    {
        if(collegeStaff.getTypeCode()==null){

            //使用手机号判断当前教师是否存在，
            CollegeStaff cStaff = collegeStaffMapper.selectCollegeByCellphone(collegeStaff.getCellphone());
            if (cStaff != null) {
                throw new CustomException("添加失败，当前教师手机号已存在！");
            }

            Member m = new Member();
            m.setCode(collegeStaff.getMemberCode());
            List<Member> ms = memberMapper.selectMemberList(m);
            if(ms.size()>0){
                throw new CustomException("添加失败，用户名已存在！");
            }

            //通过用户id查询平台管理员表数据
            College college = collegeMapper.selectCollegeById(sysUser.getDeptId().intValue());
            if (college == null) {
                throw new CustomException("添加失败，暂未查询到您的学校信息！");
            }
            //插入會員表
            Member member = new Member();
            member.setTypeCode(2l);
            member.setCode(collegeStaff.getMemberCode());
            member.setPwd("123456");
            member.setCellphone(collegeStaff.getCellphone());
            member.setCreateDt(new Date());
            memberMapper.insertMember(member);

            List<Member> members = memberMapper.selectMemberList(member);

            collegeStaff.setMemberId(members.get(0).getId().longValue());
            collegeStaff.setCollegeId(college.getCollegeId().longValue());
            collegeStaff.setCollegeCode(college.getCollegeCode());
            collegeStaff.setCollegeName(college.getCollegeName());


            return collegeStaffMapper.insertCollegeStaff(collegeStaff);

        }else if(collegeStaff.getTypeCode()==3) {

            CollegeStaff cStaff = collegeStaffMapper.selectCollegeByCellphone(collegeStaff.getCellphone());
            if(cStaff!=null){
                throw new CustomException("添加失败，当前教师手机号已存在！");
            }

            Member m = new Member();
            m.setCode(collegeStaff.getMemberCode());
            List<Member> ms = memberMapper.selectMemberList(m);
            if(ms.size()>0){
                throw new CustomException("添加失败，用户名已存在！");
            }

            Member member = new Member();
            member.setTypeCode(3l);
            member.setCode(collegeStaff.getMemberCode());
            member.setPwd("123456");
            member.setCellphone(collegeStaff.getCellphone());
            member.setCreateDt(new Date());
            memberMapper.insertMember(member);

            List<Member> members = memberMapper.selectMemberList(member);

            College college = collegeMapper.selectCollegeById(collegeStaff.getCollegeId().intValue());
            collegeStaff.setMemberId(members.get(0).getId().longValue());
            collegeStaff.setCollegeId(college.getCollegeId().longValue());
            collegeStaff.setCollegeCode(college.getCollegeCode());
            collegeStaff.setCollegeName(college.getCollegeName());


            return collegeStaffMapper.insertCollegeStaff(collegeStaff);
        }
        return 1;
    }


    /**
     * 新增学院教职员
     *
     * @param collegeStaff 学院教职员
     * @return 结果
     */

    public int importCollegeStaff(CollegeStaff collegeStaff)
    {
        return collegeStaffMapper.insertCollegeStaff(collegeStaff);
    }

    /**
     * 修改学院教职员
     *
     * @param collegeStaff 学院教职员
     * @return 结果
     */
    @Override
    public int updateCollegeStaff(CollegeStaff collegeStaff)
    {
        Member member = new Member();
        member.setId(collegeStaff.getMemberId().intValue());
        member.setCode(collegeStaff.getMemberCode());
        memberMapper.updateMember(member);
        return collegeStaffMapper.updateCollegeStaff(collegeStaff);
    }

    /**
     * 批量删除学院教职员
     *
     * @param ids 需要删除的学院教职员ID
     * @return 结果
     */
    @Override
    public int deleteCollegeStaffByIds(Integer[] ids)
    {

        for (Integer id : ids) {

            CollegeStaff collegeStaff = collegeStaffMapper.selectCollegeStaffById(id);
            memberMapper.deleteMemberById(collegeStaff.getMemberId().intValue());

        }
        return collegeStaffMapper.deleteCollegeStaffByIds(ids);
    }

    /**
     * 删除学院教职员信息
     *
     * @param id 学院教职员ID
     * @return 结果
     */
    @Override
    public int deleteCollegeStaffById(Integer id)
    {
        return collegeStaffMapper.deleteCollegeStaffById(id);
    }

    /**
     * 数据导入
     * @param CollegeStaffList
     * @param updateSupport
     * @return
     */
    @Override
    public String importCollegeStaff(List<CollegeStaff> CollegeStaffList, boolean updateSupport) {
        if (StringUtils.isNull(CollegeStaffList) || CollegeStaffList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (CollegeStaff collegeStaff : CollegeStaffList)
        {
            try
            {
                // 验证教师是否存在
                CollegeStaff u = collegeStaffMapper.selectCollegeByCellphone(collegeStaff.getCellphone());
                if (StringUtils.isNull(u))
                {

                    //当前用户的院校id
                    College college = collegeMapper.selectCollegeByCode(collegeStaff.getCollegeCode());
                    if(college==null){
                        throw new CustomException("系统暂无查询到当前院校代码");
                    }

                    //插入會員表
                    Member member = new Member();
                    member.setTypeCode(2l);
                    CollegeStaff collegeStaff1 = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()).getCollegeStaff();
                    List<CollegeStaff> list = collegeStaffMapper.selectCollegeStaffList(new CollegeStaff(){{
                        setCollegeId(collegeStaff1.getCollegeId().longValue());
                    }});
                    if(list.size()<10){
                        member.setCode(collegeStaff.getCollegeCode()+"00"+list.size()+1);
                    }else if(list.size()<100){
                        member.setCode(collegeStaff.getCollegeCode()+"0"+list.size()+1);
                    }else{
                        member.setCode(collegeStaff.getCollegeCode()+list.size()+1);
                    }

                    member.setPwd("123456");
                    member.setCellphone(collegeStaff.getCellphone());
                    member.setCreateDt(new Date());
                    memberMapper.insertMember(member);
                    List<Member> members = memberMapper.selectMemberList(member);

                    collegeStaff.setMemberId(members.get(0).getId().longValue());
                    collegeStaff.setCollegeId(college.getCollegeId().longValue());
                    collegeStaff.setCollegeCode(college.getCollegeCode());
                    collegeStaff.setCollegeName(college.getCollegeName());
                    this.importCollegeStaff(collegeStaff);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、教师 " + collegeStaff.getName() + " 导入成功");
                }
                else if (updateSupport)
                {
                    collegeStaff.setCreateDt(new Date());
                    this.updateCollegeStaff(collegeStaff);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、教师 " + collegeStaff.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、教师 " + collegeStaff.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、教师 " + collegeStaff.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public CollegeStaff selectCollegeStaffByMemberId(int member_id) {
        return collegeStaffMapper.selectCollegeByMeberId(member_id);
    }


    @Override
    public Integer updateMemberIdById(Integer id, Integer id1) {
        return collegeStaffMapper.updateMemberIdById(id,id1);
    }

    @Override
    public CollegeStaff selectCollegeStaffByCfId(Integer id) {
        return collegeStaffMapper.selectCollegeStaffByCfId(id);
    }
}
